/**
 * Copyright (C) 2011 KingCore Science & Technology CO,.LTD. All rights reserved.
 * XNS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/**
 * Copyright (C) 2002-2011 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * This software is the confidential and proprietary information of
 * WuZeven, Personal. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with WuZeven.
 */

package com.kingcore.director.search.concurrent;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.core.util.StopWatch;
import com.kingcore.framework.context.ApplicationContext;

/**
 * <p>java class file describe. </p>
 * @author Zeven on 2009-3-18
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @since	JDK5
 */

public class FileProducer implements Runnable {

	//log object
	private final static Logger log = Logger.getLogger(FileProducer.class);
	
	private static BlockingQueue<File> fielQueue = null;
	
	public FileProducer(BlockingQueue<File> p_fielQueue) {
		 fielQueue = p_fielQueue;
	}

	/**
	 * <p>java method describe</p>
	 * @author Zeven on 2009-3-18
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	static StopWatch sw = new StopWatch();
	 private static Map<File, String> localFileSearchExcludedFileMap = new HashMap<File, String>();
	 private static int count ;
	 public static final String File_End_Flag = "A:/";
	public void run() {

		Connection conn= null;
		Statement stmt =null;
		ResultSet rs=null;
		try {
			conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
			stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs=stmt.executeQuery("SELECT val from "+DirectorConstants.SYS_Setting+" WHERE KEY='"
								+ DirectorConstants.Local_File_Search_Excluded +"'");
			while (rs.next()) {
				localFileSearchExcludedFileMap.put(new File(rs.getString("val")), "val");
			}			
		} catch (Exception e){
			log.error (e);
		} finally {
			wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
		}	

		log.info( sw.watchPoint() );
		File roots[] = File.listRoots();    // 得到本地机的磁盘驱动(根)，并将其放入到一个File数组中
		String root = null;
		String filename[] = null;

		log.info( sw.watchPoint() );
			
		log.info( sw.watchPoint() );
		for (int j = 0; j < roots.length; j++) {
//			if (j!=3) {  // just for debug
//				continue;
//			}
			root = roots[j].toString();
//			root = "F:/Downloads";    // just for debug
			log.info("begin create:"+root);

			log.info( sw.watchPoint() );
			File fileDir = new File(root);
			if (localFileSearchExcludedFileMap.get(fileDir)!=null) { // excluded
				log.info(fileDir.getAbsolutePath()+" excluded.");
				continue;
			}
			filename = fileDir.list();// 获得跟目录下的所有的文件名或子目录名;(只是文件夹名或文件名，不是其结对路径)
			if (filename != null) { // 判断跟目录下是否有文件夹或子目录；
				try {
					log.info( sw.watchPoint() );
					loopFiles(fileDir.getAbsolutePath(), filename, "create"); // 传递的两个参数，前一个代表父目录，后一个为list()总的文件名
//					addFile2List(null, "create");
					
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				}
			}
			log.info("creating index file finished,file count is:" + count );
		}

		try {
			fielQueue.put( new File(File_End_Flag) ); //End //stop
			log.info("All index file loop finished." );
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	static int iCount=0;
	public static void loopFiles(String parent, String[] sd, String action) throws Exception { // 这是一个递归调用的，遍历各个文件夹

		String[] s = sd;
		if (s != null) {
			for (int i = 0; i < s.length; i++) { 
				File f = new File(parent + File.separator + s[i]); // 这里的“\\”很重要，否则f.getAbsolutePath()
				if (localFileSearchExcludedFileMap.get(f)!=null) { // excluded
					log.info(f.getAbsolutePath()+" excluded.");
					log.info( sw.watchPoint() );
					continue;
				}
				fielQueue.put( f );
//				log.info( "put to fielQueue..."+iCount++ );
				if (f.isDirectory()) {
					String[] ss = f.list();
					loopFiles(f.getAbsolutePath(), ss, action);// 递归调用；

				} 
				else { 
					count++; 
				}
			}
		}

	}
}
